/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JanelaPrincipal.java
 *
 * Created on May 31, 2011, 11:24:44 AM
 */
package cataletra.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import javax.swing.JPanel;

/**
 *
 * @author arthur
 */
public class JanelaPrincipal extends javax.swing.JFrame {
    
    //----PAINEIS----
    private PainelCacaPalavras painelCacaPalavras;
    private PainelConfiguracao painelConfiguracao;
    private PainelModoJogo painelModoJogo;
    private PainelLateral painelLateral;
    private JPanel painelVazio;
    
    //------TIMER-------
    private int tempo;
    private Timer timer;
    
    private boolean jogando;
    
    //--------MODO DE JOGO--------
    private int modoJogo;
    
    public final int JOGO_NORMAL = 0;
    public final int JOGO_RAPIDO = 1;
    
    private int pontuacao;
    private int nivelAtual;

    /** Creates new form JanelaPrincipal */
    public JanelaPrincipal() {
        initComponents();
        
        this.reiniciar();
        
        tempo = 1;
        
        labelTimer.setBorder(javax.swing.BorderFactory.createEmptyBorder(3, 3, 3, 6));
        labelTimer.setForeground(Color.red);
        labelTimer.setFont(new Font("Tahoma", Font.BOLD, 14));
        
        this.centralizar();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        barraSuperior = new javax.swing.JToolBar();
        botaoNovoJogo = new javax.swing.JButton();
        botaoReiniciar = new javax.swing.JButton();
        botaoEditarTemas = new javax.swing.JButton();
        botaoPausar = new javax.swing.JButton();
        botaoDesistir = new javax.swing.JButton();
        botaoSair = new javax.swing.JButton();
        barraInferior = new javax.swing.JPanel();
        labelTimer = new javax.swing.JLabel();
        painelSeparacao = new javax.swing.JSplitPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Cata Letra");
        setMinimumSize(new java.awt.Dimension(600, 450));

        barraSuperior.setFloatable(false);
        barraSuperior.setRollover(true);

        botaoNovoJogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cataletra/images/new.png"))); // NOI18N
        botaoNovoJogo.setText("Novo Jogo");
        botaoNovoJogo.setFocusable(false);
        botaoNovoJogo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clicarBotaoNovoJogo(evt);
            }
        });
        barraSuperior.add(botaoNovoJogo);

        botaoReiniciar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cataletra/images/reiniciar.png"))); // NOI18N
        botaoReiniciar.setText("Reiniciar");
        botaoReiniciar.setFocusable(false);
        botaoReiniciar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clicarBotaoReiniciar(evt);
            }
        });
        barraSuperior.add(botaoReiniciar);

        botaoEditarTemas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cataletra/images/editar.png"))); // NOI18N
        botaoEditarTemas.setText("Editar");
        botaoEditarTemas.setFocusable(false);
        botaoEditarTemas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clicarBotaoEditarTemas(evt);
            }
        });
        barraSuperior.add(botaoEditarTemas);

        botaoPausar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cataletra/images/pause22.png"))); // NOI18N
        botaoPausar.setText("Pausar");
        botaoPausar.setFocusable(false);
        botaoPausar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clicarBotaoPausar(evt);
            }
        });
        barraSuperior.add(botaoPausar);

        botaoDesistir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cataletra/images/desistir22.png"))); // NOI18N
        botaoDesistir.setText("Desistir");
        botaoDesistir.setFocusable(false);
        botaoDesistir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clicarBotaoDesistir(evt);
            }
        });
        barraSuperior.add(botaoDesistir);

        botaoSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cataletra/images/sair22.png"))); // NOI18N
        botaoSair.setText("Sair");
        botaoSair.setFocusable(false);
        botaoSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clicarBotaoSair(evt);
            }
        });
        barraSuperior.add(botaoSair);

        getContentPane().add(barraSuperior, java.awt.BorderLayout.NORTH);

        barraInferior.setLayout(new java.awt.BorderLayout());

        labelTimer.setText("Timer");
        barraInferior.add(labelTimer, java.awt.BorderLayout.LINE_END);

        getContentPane().add(barraInferior, java.awt.BorderLayout.PAGE_END);

        painelSeparacao.setDividerLocation(200);
        painelSeparacao.setDividerSize(2);
        getContentPane().add(painelSeparacao, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void clicarBotaoEditarTemas(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clicarBotaoEditarTemas
        JanelaEditorDeTemas janela = new JanelaEditorDeTemas(this, true);
        
        janela.setVisible(true);
    }//GEN-LAST:event_clicarBotaoEditarTemas

    private void clicarBotaoDesistir(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clicarBotaoDesistir
        this.desistir();
    }//GEN-LAST:event_clicarBotaoDesistir

    private void clicarBotaoSair(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clicarBotaoSair
        if(jogando){
            timer.stop();
            this.painelSeparacao.setRightComponent(painelVazio);
        }
        int resp = JOptionPane.showConfirmDialog(this, "Tem certeza que deseja sair do Cata-Letra?", "Sair", JOptionPane.YES_NO_OPTION);
        if(resp == JOptionPane.YES_OPTION){
            System.exit(1);
        } else if(resp == JOptionPane.NO_OPTION && jogando){
            timer.start();
            this.painelSeparacao.setRightComponent(painelCacaPalavras);
        }
    }//GEN-LAST:event_clicarBotaoSair

    private void clicarBotaoPausar(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clicarBotaoPausar
        if(timer.isRunning()){
            timer.stop();
            this.painelSeparacao.setRightComponent(painelVazio);
            this.botaoPausar.setText("Continuar");
            this.botaoPausar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cataletra/images/play22.png")));
        } else {
            timer.start();
            tempo++;
            this.painelSeparacao.setRightComponent(painelCacaPalavras);
            this.botaoPausar.setText("Pausar");
            this.botaoPausar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cataletra/images/pause22.png")));
        }
    }//GEN-LAST:event_clicarBotaoPausar

    private void clicarBotaoNovoJogo(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clicarBotaoNovoJogo
        if(jogando){
            timer.stop();
            this.painelSeparacao.setRightComponent(painelVazio);
            
            int resp = JOptionPane.showConfirmDialog(this, "Tem certeza que deseja começar um novo jogo?", "Novo", JOptionPane.YES_NO_OPTION);
            if(resp == JOptionPane.YES_OPTION){
                reiniciar();
            } else {
                timer.start();
                this.painelSeparacao.setRightComponent(painelCacaPalavras);                
            }
        }
        
        reiniciar();
    }//GEN-LAST:event_clicarBotaoNovoJogo

    private void clicarBotaoReiniciar(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clicarBotaoReiniciar
        this.painelCacaPalavras.reiniciar();
        this.painelLateral.setPalavras(this.painelCacaPalavras.getCacaPalavras().getPalavrasUsadas());
        iniciarTimer(0, 1);
        
        this.botaoReiniciar.setVisible(false);
        this.botaoDesistir.setVisible(true);
        this.botaoPausar.setVisible(true);        
    }//GEN-LAST:event_clicarBotaoReiniciar

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new JanelaPrincipal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel barraInferior;
    private javax.swing.JToolBar barraSuperior;
    private javax.swing.JButton botaoDesistir;
    private javax.swing.JButton botaoEditarTemas;
    private javax.swing.JButton botaoNovoJogo;
    private javax.swing.JButton botaoPausar;
    private javax.swing.JButton botaoReiniciar;
    private javax.swing.JButton botaoSair;
    private javax.swing.JLabel labelTimer;
    private javax.swing.JSplitPane painelSeparacao;
    // End of variables declaration//GEN-END:variables

    protected final void reiniciar(){
        tempo = 0;
        pontuacao = 0;
        
        jogando = false;
        
        this.painelConfiguracao = new PainelConfiguracao();
        this.painelModoJogo = new PainelModoJogo();
        this.painelVazio = new JPanel();
        
        this.painelSeparacao.setLeftComponent(this.painelModoJogo);
        this.painelSeparacao.setRightComponent(painelVazio);
        this.painelSeparacao.setDividerLocation(200);
        
        this.botaoReiniciar.setVisible(false);
        this.botaoEditarTemas.setVisible(true);
        this.botaoPausar.setVisible(false);
        this.botaoDesistir.setVisible(false);        
        this.labelTimer.setVisible(false);
        
        this.setSize(new Dimension(600,450));
    }

    private void centralizar(){
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

        // Determine the new location of the window
        int w = this.getSize().width;
        int h = this.getSize().height;
        int x = (dim.width - w) / 2;
        int y = (dim.height - h) / 2;

        // Move the window
        this.setLocation(x, y);
    }
    
    public int getModoJogo() {
        return modoJogo;
    }

    public void setModoJogo(int modoJogo) {
        this.modoJogo = modoJogo;
    }
    
    public PainelCacaPalavras getPainelJogo() {
        return painelCacaPalavras;
    }
    
    public PainelConfiguracao getPainelConfiguracao() {
        return painelConfiguracao;
    }

    public PainelLateral getPainelLateral() {
        return painelLateral;
    }
    
    public void iniciarJogo(String tema, ArrayList palavras, int linhas, int colunas, int qtdePalavras){
        iniciarJogo(new PainelCacaPalavras(palavras, linhas, colunas, qtdePalavras), tema);  
        iniciarTimer(0, 1);      
        
        this.modoJogo = this.JOGO_RAPIDO;
        this.centralizar();
    }
    
    public void iniciarJogo(){
        iniciarJogo(new PainelCacaPalavras(), "");
        iniciarTimer(180, -1);
        
        this.setSize(new Dimension(720, 540));
        
        this.nivelAtual = 1;
        
        this.modoJogo = this.JOGO_NORMAL;
        this.centralizar();
    }
    
    public void iniciarJogo(PainelCacaPalavras painelCP, String tema){
        this.painelCacaPalavras = painelCP;
        if(tema.equals("")){
            this.painelLateral = new PainelLateral(1, painelCacaPalavras.getCacaPalavras().getPalavrasUsadas());
        } else {
            this.painelLateral = new PainelLateral(tema, painelCacaPalavras.getCacaPalavras().getPalavrasUsadas());
        }        
        
        this.painelSeparacao.setRightComponent(painelCacaPalavras);
        
        JPanel painel = new JPanel();
        painel.setLayout(new BorderLayout());
        painel.add(painelLateral, BorderLayout.NORTH);
        this.painelSeparacao.setLeftComponent(painel);
        
        this.botaoEditarTemas.setVisible(false);
        this.botaoDesistir.setVisible(true);
        this.botaoPausar.setVisible(true);
        
        this.jogando = true;
    }
    
    public void reiniciarPartida(){
        this.painelLateral.reiniciar();
        this.painelCacaPalavras.reiniciar();
        this.iniciarTimer(120 + 60 * nivelAtual, -1);
        
        this.botaoEditarTemas.setVisible(false);
        this.botaoDesistir.setVisible(true);
        this.botaoPausar.setVisible(true);
    }
    
    public void proximoNivel(int tempoExtra){
        this.painelCacaPalavras.proximoNivel();
        this.nivelAtual++;
        this.iniciarTimer(120 + 60 * nivelAtual + tempoExtra, -1);
        
        this.painelLateral = new PainelLateral(nivelAtual, painelCacaPalavras.getCacaPalavras().getPalavrasUsadas());
        JPanel painel = new JPanel();
        painel.setLayout(new BorderLayout());
        painel.add(painelLateral, BorderLayout.NORTH);
        this.painelSeparacao.setLeftComponent(painel);
        
        this.centralizar();
    }
    
    public void partidaRapida(){
        this.painelSeparacao.setLeftComponent(this.painelConfiguracao);
    }
    
    private void desistir(){
        timer.stop();
        this.jogando = false;
        this.painelSeparacao.setRightComponent(painelVazio);
        int resp = JOptionPane.showConfirmDialog(this, "Tem certeza que deseja desistir?", "Sair", JOptionPane.YES_NO_OPTION);
        this.painelSeparacao.setRightComponent(painelCacaPalavras);
        if(resp == JOptionPane.YES_OPTION){
            if(this.modoJogo == this.JOGO_NORMAL){
                tempo = 0;
                this.perdeu(true);
            } else {
                this.botaoReiniciar.setVisible(true);
                this.botaoDesistir.setVisible(false);
                this.botaoPausar.setVisible(false);
                this.painelCacaPalavras.mostrarResposta();
            }
        } else {
            timer.start();            
        }
    }
    
    public void punir(int segs){
        if(this.modoJogo == this.JOGO_NORMAL){
            tempo -= segs;
        } else {
            tempo += segs;
        }
        this.painelLateral.punir();
        if(tempo <= 0) timer.stop();
        this.atualizaTimer(tempo);
    }
    
    private void atualizaTimer(int t){
        if(t <= 0){
            labelTimer.setText("00:00");
            this.perdeu(false);
        } else if(t < 10) {
            labelTimer.setText("00:0" + (t++));
        } else if(t >= 10 && t < 60) {
            labelTimer.setText("00:" + (t++));
        } else if(t >= 60 && t < 600 && t % 60 < 10) {
            labelTimer.setText("0" + (int) (t++) / 60 + ":0" + (t - 1) % 60);
        } else if(t >= 60 && t < 600) {
            labelTimer.setText("0" + (int) (t++) / 60 + ":" + (t - 1) % 60);
        } else if(t >= 600 && t < 3600 && ((t - 1) % 600) % 60 < 10) {
            labelTimer.setText((int) (t++) / 60 + ":0" + ((t - 1) % 600) % 60);
        } else if(t >= 600 && t < 3600) {
            labelTimer.setText((int) (t++) / 60 + ":" + ((t - 1) % 600) % 60);
        }
    }
    
    private void iniciarTimer(int tempoInicial, final int variacao) {
        ActionListener action = new ActionListener() {

            @Override
            public void actionPerformed(java.awt.event.ActionEvent e) {
                tempo = tempo + variacao;
                atualizaTimer(tempo);
            }
        };
        
        labelTimer.setVisible(true);
        labelTimer.setText("00:00");

        timer = new Timer(1000, action);
        timer.start();
        
        tempo = tempoInicial;
    }
    
    public void ganhou(){
        if(this.modoJogo == this.JOGO_NORMAL){
            timer.stop();
            int pontos = this.pontuacao;
            int qtdePalavrasAchadas = this.painelCacaPalavras.getCacaPalavras().getQtdePalavras();
            this.pontuacao += tempo * 5 + qtdePalavrasAchadas * 10;
            JanelaPontos janelaPontos = new JanelaPontos(this, true, pontos, qtdePalavrasAchadas, this.tempo);
            janelaPontos.setVisible(true);
        } else {
            String msg = "Você completou o caça-palavras em " + labelTimer.getText();
            JOptionPane.showMessageDialog(this, msg, "Parabéns!", JOptionPane.INFORMATION_MESSAGE);   

            this.jogando = false;         
            botaoReiniciar.setVisible(true);
            botaoDesistir.setVisible(false);
            botaoPausar.setVisible(false);   
            timer.stop();
        }
    }

    private void perdeu(boolean desistiu) {
        if(this.modoJogo == this.JOGO_RAPIDO) botaoReiniciar.setVisible(true);
        botaoDesistir.setVisible(false);
        botaoPausar.setVisible(false);
        timer.stop();
        painelCacaPalavras.mostrarResposta();
        
        JanelaPontos janelaPontos = new JanelaPontos(this, true, this.pontuacao, 
                this.painelLateral.getQtdePalavrasAchadas(), desistiu);
        janelaPontos.setVisible(true);
    }

    public int getPontuacao() {
        return pontuacao;
    }

    public int getTempo() {
        return tempo;
    }
    
    
}
